<?php

namespace App\Service;
use App\Service\CommService;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CachePut;

use Hyperf\DbConnection\Db;
use App\Service\UserService;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

class UserStepsService
{

    private UserService $userService;
    private CommService $commService;
    private $redisService;

    // 在构造函数声明参数的类型，Hyperf 会自动注入对应的对象或值
    public function __construct(UserService $userService,CommService $commService)
    {
        $this->userService = $userService;
        $this->commService = $commService;
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    public function get_steps(int $user_id)
    {
        echo "用户ID".$user_id.PHP_EOL;
        $where = [
            ['user_id', '=', $user_id],
            ['sdate', '=', date("Ymd")],
        ];
        $steps = Db::table('data_user_steps')->where($where)->select('id','steps_number',"wx_last_steps","wx_steps","user_id")->first();
        if (empty($steps)){
            $steps["steps_number"] = 0;
            $steps["wx_last_steps"] = 0;
            $steps["wx_steps"] = 0;
            $steps["user_id"] = $user_id;
            $steps["sdate"] = date("Ymd");
            Db::table('data_user_steps')->insertGetId(
                $steps
            );
            unset($steps["sdate"]);
            $steps = (object)$steps;
        }
        # 奖励步数
        $reward_steps_list = self::user_reward_steps($user_id);
        $app_cofig = $this->userService->get_app_config_list();
        $steps->steps_matrixing =$app_cofig->steps_scale;
        # 还有列表
        $friend_list = $this->userService->friend_list($user_id);
        print_r($friend_list);
        echo "好友人数的".PHP_EOL;
        $friend_list_array = $this->commService->object_to_array($friend_list);
        $invite_friends_jiacheng = 0;
        if (count((array)$friend_list)>0){
            $invite_friends_jiacheng = count($friend_list_array) *2;
            if ($invite_friends_jiacheng >100){
                $invite_friends_jiacheng = 100;
            }
        }
        if ($invite_friends_jiacheng>0){
            foreach ($friend_list as $key=>$value){
                if (empty(strstr($value->headimg , 'http'))) {
                    $value->headimg = "https://jingyios.oss-cn-beijing.aliyuncs.com/appimg/mo_touxiang.jpg";
                }
            }
        }
        $steps->reward_steps_list = $reward_steps_list;
        $steps->friend_list = $friend_list;
        $steps->user_info = $this->userService->get_user_info_info($user_id);
        $steps->invite_friends_title = "今日步数加成".$invite_friends_jiacheng."%";
        return $steps;
    }

    /**
     * 奖励用户步数
     * @param int $user_id
     * @return \Hyperf\Utils\Collection|object
     */
    public function user_reward_steps(int $user_id){
        $where = [
            ['user_id', '=', $user_id],
            ['sdate', '=', date("Ymd")],
            ['status', '=', 1],
        ];
        $reward_steps = Db::table('data_user_reward_steps')->where($where)->select('id','name','steps_number',"user_id")->get();
        $is_emyp = count($reward_steps);
        if (empty($is_emyp)){
            $reward_steps = (object)[];
        }
        return $reward_steps;
    }

    public function add_user_reward_steps($data){
        $id = Db::table('data_user_reward_steps')->insertGetId(
            $data
        );
        return $id;
    }

    public function getUserRewardStepsInfo($data){
        $user_id = (int)$data["user_id"];
        $user_steps_id = (int)$data["user_steps_id"];
        $where = [
            ['user_id', '=', $user_id],
            ['id', '=', $user_steps_id],
            ['status', '=', 1],
            ['sdate', '=', date("Ymd")],
        ];

        $reward_steps = Db::table('data_user_reward_steps')->where($where)->select('id','steps_number',"user_id")->first();
        return (array)$reward_steps;
    }

    public function UpdateUserRewardSteps($reward_steps_id){
        Db::table("data_user_reward_steps")->where(["id"=>$reward_steps_id])->update(["status"=>0]);
    }
    public function addUserStepsNumber($data){
        $user_id = (int)$data["user_id"];
        $where = [
            ['user_id', '=', $user_id],
            ['sdate', '=', date("Ymd")],
        ];
        $steps = Db::table('data_user_steps')->where($where)->select('id','steps_number',"wx_last_steps","wx_steps","user_id")->first();
        $steps_info = (array)$steps;
        if ($steps_info){
           $rect_status =  Db::table('data_user_steps')->where($where)->update(['steps_number' =>(int)$steps_info["steps_number"] +(int)$data["steps_number"]]);
        }else{
            $adddata["steps_number"] = $data["steps_number"];
            $adddata["wx_last_steps"] = 0;
            $adddata["wx_steps"] = 0;
            $adddata["user_id"] = $user_id;
            $adddata["sdate"] = date("Ymd");
            $rect_status = Db::table('data_user_steps')->insertGetId(
                $adddata
            );
        }
        return $rect_status;
    }

    // 兑换积分
    public function convert_integral(int $user_id){
        # 查询当前多少积分
        $where = [
            ['user_id', '=', $user_id],
            ['sdate', '=', date("Ymd")],
        ];
        $config = $this->userService->get_app_config_list();
        $steps_info = Db::table('data_user_steps')->where($where)->select('id','steps_number',"wx_last_steps","wx_steps","user_id","convert_steps")->first();
        $steps_info = (array)$steps_info;
        if ($steps_info){
            # 查询当前可以兑换积分数量
            if ($steps_info["steps_number"]>=10)
            {
                if ($steps_info["convert_steps"]>=$config->max_steps){
                    return [
                        "code"=>2015,
                        "message"=>"每天最大可兑换".$config->max_steps."步数",
                        "content"=>(object)[],
                    ];
                }else{
                    $zongbushu = (int)$steps_info["steps_number"] + (int)$steps_info["convert_steps"];
                    if ($zongbushu>$config->max_steps){
                        $steps_number = (int)$config->max_steps - (int)$steps_info["convert_steps"];
                    }else{
                        $steps_number = (int)$steps_info["steps_number"];
                    }
                    # 步数积分换算
                    $integral =  number_format($steps_number * $config->steps_scale,2);
                    $user_info = $this->userService->getByUserIdUserInfo($user_id);
                    # 修改的用户步数
                    Db::table("data_user")->where(["id"=>$user_id])->update(["integral"=>$user_info->integral + $integral]);
                    $this->userService->update_user_info($user_id);
                    # 添加记录
                    $this->userService->add_user_integral_log(["name"=>$steps_info["steps_number"]."步数兑换欢乐币","user_id"=>$user_id,"integral"=>$integral,"stype"=>1,"integral_type"=>2]);
                    # 修改当前步数状态
                    Db::table("data_user_steps")->where(["id"=>$steps_info["id"]])->update(
                        [
                            "steps_number"=>$steps_info["steps_number"] - $steps_number,"wx_last_steps"=>$steps_info["wx_steps"],"convert_steps"=>$steps_info["convert_steps"] + $steps_number
                        ]
                    );

                    return [
                        "code"=>10000,
                        "message"=>"兑换成功",
                        "content"=>[
                            "user_steps_number"=>$steps_info["steps_number"] - $steps_number,
                            "integral"=>$integral,
                            "user_integral"=>number_format($user_info->integral + $integral,2),
                        ],
                    ];
                }

            }else{
                return [
                    "code"=>2016,
                    "message"=>"兑换步数不足10步",
                    "content"=>(object)[],
                ];
            }
        }
        return [
            "code"=>2016,
            "message"=>"兑换步数不足10步",
            "content"=>(object)[],
        ];
    }


    public function convert_integral_check(int $user_id){
        # 查询当前多少积分
        $where = [
            ['user_id', '=', $user_id],
            ['sdate', '=', date("Ymd")],
        ];
        $config = $this->userService->get_app_config_list();
        $steps_info = Db::table('data_user_steps')->where($where)->select('id','steps_number',"wx_last_steps","wx_steps","user_id","convert_steps")->first();
        $steps_info = (array)$steps_info;
        # 查询当前可以兑换积分数量
        $zongbushu = (int)$steps_info["steps_number"] + (int)$steps_info["convert_steps"];
        if ($zongbushu>$config->max_steps){
            $steps_number = (int)$config->max_steps - (int)$steps_info["convert_steps"];
        }else{
            $steps_number = (int)$steps_info["steps_number"];
        }
        # 步数积分换算
        $integral =  number_format($steps_number * $config->steps_scale,2);
        if ($zongbushu>$config->max_steps){
            if ($steps_number == 0){
                $title = "今日兑换步数已超过".$config->max_steps."步，请明天再来兑换";
            }else{
                $title = "每日最高可兑换".$config->max_steps."步，当前只能兑换".$steps_number."步，可兑换".$integral."欢乐币，是否立即兑换";
            }
        }else{
            $title = "当前步数".$steps_number."，可兑换".$integral."欢乐币是否立即兑换";
        }

        return [
            "code"=>10000,
            "message"=>"成功",
            "content"=>[
                "title"=>$title,
            ],
        ];
    }

    // 同步微信步数
    public function sync_steps(int $user_id,int $steps_number){
        # 查询当前多少积分
        $where = [
            ['user_id', '=', $user_id],
            ['sdate', '=', date("Ymd")],
        ];
        $config = $this->userService->get_app_config_list();
        $steps_info = Db::table('data_user_steps')->where($where)->select('id','steps_number',"wx_last_steps","wx_steps","user_id","convert_steps")->first();
        $steps_info = (array)$steps_info;
        //奖励步数
        $jiangli_steps_number = 0;
        if ($steps_info) {
            if ($steps_number >$config->max_steps){
                echo "数据到这里了".PHP_EOL;
                $jiangli_steps_number = (int)$config->max_steps -  (int)$steps_info["wx_steps"];
                if ($jiangli_steps_number<0){
                    $jiangli_steps_number = 0;
                }
                echo $jiangli_steps_number.PHP_EOL;
            }else{
                $jiangli_steps_number =  $steps_number - (int)$steps_info["wx_steps"];
                if($jiangli_steps_number < 0){
                    $jiangli_steps_number = 0;
                }
            }
            $steps_number = $steps_number - (int)$steps_info["wx_steps"];
            if ($steps_number<0){
                $steps_number = 0;
            }
            $user_steps_number = (int)$steps_info["steps_number"]+$steps_number;
            if ($steps_number>0){
                Db::table('data_user_steps')->where(["id"=>$steps_info["id"]])->update([
                    "steps_number"=>$user_steps_number,
                    "wx_steps"=>(int)$steps_info["wx_steps"] +$steps_number,
                ]);
            }
            # 查看是否推广人
            $user_info = $this->userService->user_info($user_id);
            echo "查看是否推广人用户基本信息:".PHP_EOL;
//            print_r($user_info).PHP_EOL;
            if ($user_info->pid1 > 0){
                # 微信步数加成
                $redis_key = "jingy:user:steps:reward:".date("Ymd").":".$user_info->pid1;
                $user_keys = $this->redisService->hKeys($redis_key);
                $rect_staus = 1;
                if (count($user_keys)>=50){
                    if (!in_array($user_id,$user_keys)){
                        $rect_staus = 0;
                    }
                }
                if ($rect_staus == 1 && $jiangli_steps_number>10){
                    $this->redisService->hSet($redis_key,(string)$user_id,"1");
                    $this->redisService->expire($redis_key,86400);
                    $ticheng_number = round($jiangli_steps_number * 0.02);
                    if ($ticheng_number>0){
                        $reward_steps["name"] = "好友加成";
                        $reward_steps["steps_number"] = $ticheng_number;
                        $reward_steps["user_id"] = $user_info->pid1;
                        $reward_steps["sdate"] = date("Ymd");
                        $reward_steps["types_id"] = 2;
                        $this->userService->addSuserUserRewardSteps($reward_steps);
                        unset($reward_steps);
                    }
                }

            }

        }else{
            Db::table('data_user_steps')->insertGetId([
                "steps_number"=>$steps_number,
                "wx_steps"=>$steps_number,
                "user_id"=>$user_id,
                "sdate"=>date("Ymd"),
            ]);
            $user_steps_number = $steps_number;
        }
        $rec_data = [
            "code"=>10000,
            "message"=>"微信步数同步成功",
            "content"=>["user_steps_number"=>$user_steps_number],
        ];
        return $rec_data;
    }
}